package org.casper.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.casper.bean.User;
import org.casper.service.UserService;

/**
 * 跳转管理登录页面（也是管理员首页的servlet）
 */
public class IndexServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private HttpSession session = null;
	private UserService userService = new UserService();
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		session = request.getSession();
		Cookie[] cookies = request.getCookies();
		User user = new User();
		if(cookies!=null){											//获取存取在Cookie的端的用户名和密码
			for (Cookie cookie : cookies) {
				if(cookie.getName().equals("email")){
					user.setEmail(cookie.getValue());
				}else if(cookie.getName().equals("pass")){
					user.setPass(cookie.getValue());
				}
			}
			if(user!=null){
				user.setLastip(request.getRemoteAddr());			//设置本次登录的ip
				User newUser = userService.adminLogin(user);
				if(newUser!=null){
					session.setAttribute("user", newUser);
					response.sendRedirect("BoardServlet?op=adminIndex");		//跳转到管理员主页
				}else{
					response.sendRedirect("admin-login.jsp");		//跳转到管理员登录页面
				}
			}else{
				response.sendRedirect("admin-login.jsp");			//跳转到管理员登录页面
			}
		}else{
			response.sendRedirect("admin-login.jsp");				//跳转到管理员登录页面
		}
	}
       
	

}
